'''
Author: Simon
Date: 2021-12-22 21:09:47
LastEditTime: 2022-02-21 18:55:33
LastEditors: Please set LastEditors
FilePath: /UICtimeTableToICS/login.py
'''
import json
from typing import final
from markupsafe import string
import requests
import bs4
from bs4 import BeautifulSoup

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

def login_post(url, j_username, j_password, target_url):

    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        'Connection': 'keep-alive'
    }
    
    # post_data = {
    #     "j_target_url": r"https://mis.uic.edu.hk/mis/usr/index.do",
    #     "j_username": j_username,
    #     "j_password": j_password,
    #     'usertype': 'student'
    # }
    
    form_data = {
        'j_target_url': '/usr/index.do',
        'j_username': j_username,
        'j_password': j_password,
        'usertype': 'on',
        'x': '16',
        'y': '16'
    }
    
    session = requests.session()
    login_page = session.post(url, data=form_data, headers=headers, verify=False)
    
    print('Login: {}'.format(login_page.status_code))
    
    # print(login_page.text)
    
    # print target url
    target_html = session.get(target_url, headers=headers, verify=False)
    # print(target_html.text)
    
    result = target_html.text
    return result
    
    
def saveResult(result_path, result):
    with open("result/result.txt", "w", encoding='utf-8') as f:
        f.write(result)
        f.close()
    print("Save Complete!")
        
        
def getInfomation(result):
    datalist = []
    soup = bs4.BeautifulSoup(result, "html.parser")
    for item in soup.find_all('tr'):
        data = []
        for t in item.find_all('th', class_="socketleft"):
            
            # course time
            ctime = t.text
            # print(ctime)
            data.append(ctime)

        for c in item.find_all('td', class_="socketspace"):
            ctext = str(c.text)
            # ctext = ctext.replace(' ', '').replace('\n', '').replace('\r', '').replace('\t', '').replace('\xa0', ' ')
            
            # print(c.stripped_strings)
            strings = list(c.stripped_strings)
            course_list = []
            if len(strings) != 0:
                # print(strings[1])
                course_name = strings[0]
                course_loc = strings[1]
                course_list.append(course_name)
                course_list.append(course_loc)
            else:
                # print(" ")
                course_list.append(" ")
            # data.append(ctext)
            
            # Tindex = ctext.rfind('T')
            # # print("T: {}".format(ctext.rfind('T')))     # find last T index
            
            # course_name = ctext[:Tindex]
            
            # # print(course_name)
            # course_loc = ctext[Tindex:]
            
            # course_list = []
            # if ctext == ' ':
            #     course_list.append(' ')
            # else:
            #     course_list.append(course_name)
            #     course_list.append(course_loc)
            
            data.append(course_list)
        
        if data:
            datalist.append(data)
            
    # print(datalist)
    return datalist
    
def finalData(datalist):
    finalResult = []
    
    for data in datalist:
        d = {}
        
        result = []
        
        # print(i)
        
        weekDate = 1
        # print(data[0])

        d['course_time'] = data[0]
        
        for q in data:
            # print(type(q) == str)
            
            if type(q) != str:
                
                if ' ' not in q:
                    p_temp = {
                                "weekday": weekDate,
                                "course_name": q[0],
                                "course_place": q[1],
                            }
                else:
                    p_temp = {
                                "weekday": weekDate,
                                "course_name": ' ',
                                "course_place": ' ',
                            }
                result.append(p_temp)
                weekDate = weekDate + 1
        d['courselist'] = result
        finalResult.append(d)
        
    # print(finalResult)
    
    json_result = json.dumps({"data":finalResult})
    print(json_result)
    return finalResult
    
if __name__ == '__main__':
    url = 'https://mis.uic.edu.cn/mis/usr/login.sec'
    target_url = 'https://mis.uic.edu.cn/mis/student/tts/timetable_min.do'
    # result = login_post(url=url, j_username="x", j_password="x", target_url=target_url)
    result = login_post(url=url, j_username="p930026144", j_password="Yhan010917", target_url=target_url)

    result_path = 'result/result.txt'
    
    # saveResult(result_path=result_path, result=result)

    datalist = getInfomation(result)
    
    finalData(datalist)
